﻿using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using DevExpress.XtraTab;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Marmat.Foundation;
using System.Net;
using System.IO;
using Marmat.FrameWork;

namespace Marmat.Template.WinForm
{

    /// <summary>
    /// 构建窗体实例。
    /// </summary>
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm, IMainForm
    {
        private readonly IMeunManagement meunService;

        /// <summary>
        /// 构建窗体实例。
        /// </summary>
        protected MainForm() : this(null)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="meunService"></param>
        public MainForm(IMeunManagement meunService)
        {
            InitializeComponent();

            if (this.DesignMode)
                return;
            this.ShowSkinButton = false;
            var upgrade = SystemCommand.GetService<IUpgrade>();
            if (upgrade != null)
            {
                this.settingBtn.Visibility = BarItemVisibility.Always;
                var item = new BarButtonItem();
                item.Caption = "检查升级";
                item.ItemClick += (order, args) =>
                {
                    if (upgrade.CheckUpgrade())
                    {
                        if (MessageBox.Show("您的软件有新的版本，是否更新？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            upgrade.Upgrade();
                        }
                    }
                    else
                    {
                        MessageBox.Show("您的软件已是最新版本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                };
                this.settingBtn.AddItem(item);
            }

            if (SystemCommand.GetService<IChangePassword>() is not null && SystemCommand.GetService<IChangePasswordForm>() is not null)
            {
                this.settingBtn.Visibility = BarItemVisibility.Always;
                var item = new BarButtonItem();
                item.Caption = "更改密码";
                item.ItemClick += (_, _) =>
                {
                    var changePasswordForm = SystemCommand.GetService<IChangePasswordForm>();
                    if (changePasswordForm.ShowDialog(SystemCommand.GetUserID()))
                    {
                        MessageBox.Show("密码修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                };
                this.settingBtn.AddItem(item);
            }
            this.meunService = meunService;
            this.settingBtn.Visibility = this.settingBtn.ItemLinks.Count > 0 ? BarItemVisibility.Always : BarItemVisibility.Never;
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            companyName.Caption = $"{Application.CompanyName}    V{Application.ProductVersion}";
        }

        private void MainForm2_Load(object sender, EventArgs e)
        {
            if (this.meunService != null)
            {
                List<IMenu> menus = meunService.ToList();
                this.BuildMenu(menus);
            }

            // 初始化工作台
            var workBench = Marmat.FrameWork.SystemCommand.GetService<IWorkBench>();
            if (workBench is not null)
            {
                var panel = workBench.GetWorkBenchPanel();
                if (panel is System.Windows.Forms.Form form)
                    this.AddForm(form);
            }
        }

        /// <summary>
        /// 添加设置里面的按钮项。
        /// </summary>
        /// <param name="item"></param>
        public void AddSetingItem(DevExpress.XtraBars.BarButtonItem item)
        {
            this.settingBtn.AddItem(item);
        }

        /// <summary>
        /// 生成菜单
        /// </summary>
        /// <param name="menus"></param>
        private void BuildMenu(List<IMenu> menus)
        {
            this.BuildMenu(null, menus, this.accordionControl1.Elements);
        }

        /// <summary>
        /// 根据菜单集合生成对应的菜单项
        /// </summary>
        /// <param name="item"></param>
        /// <param name="menus"></param>
        /// <param name="elements"></param>
        private void BuildMenu(IMenu item, List<IMenu> menus, AccordionControlElementCollection elements)
        {
            if (item is null)
            {
                foreach (IMenu menu in menus.Where(x => x.Parent == null).OrderBy(x => x.Sequnce))
                {
                    BuildMenu(menu, menus, elements);
                }
                return;
            }
            IEnumerable<IMenu> items = menus.Where(x => x.Parent == item.Name).OrderBy(x => x.Sequnce);
            DevExpress.XtraBars.Navigation.AccordionControlElement barItem = new AccordionControlElement();

            foreach (var menu in items)
            {
                BuildMenu(menu, menus, barItem.Elements);
            }
            if (barItem.Elements.Count == 0)
            {
                barItem.Style = DevExpress.XtraBars.Navigation.ElementStyle.Item;
            }
            barItem.Name = item.Name;

            IFileManager manager = Marmat.FrameWork.SystemCommand.GetService<IFileManager>();
            if (manager is not null && !string.IsNullOrEmpty(item.Uri))
            {
                string uri = manager.GenerateUri(item.Uri);
                var webClient = new WebClient();
                webClient.DownloadDataCompleted += this.WebClient_DownloadDataCompleted;
                webClient.DownloadDataAsync(new Uri(uri), barItem);
            }
            barItem.Text = string.IsNullOrEmpty(item.Text) ? item.Name : item.Text;
            barItem.Tag = item;
            elements.Add(barItem);
        }

        private void WebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error is null && e.UserState is DevExpress.XtraBars.Navigation.AccordionControlElement item)
            {
                Action action = () =>
                {
                    using (MemoryStream ms = new MemoryStream(e.Result))
                    {
                        Image img = Image.FromStream(ms);//生成图片
                        item.Image = img;
                    }
                };
                this.Invoke(action);
                if (sender is WebClient webClient)
                    webClient.Dispose();
            }
        }

        /// <summary>
        /// 点击菜单时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void accordionControl1_ElementClick(object sender, ElementClickEventArgs e)
        {
            if (e.Element.Tag is IMenu menu)
                this.meunService?.ItemClick(menu);
        }

        /// <summary>
        /// 获取或设置选定的窗体名称
        /// </summary>
        string IMainForm.SelectedFormName
        {
            get => this.tabPanelControl1.SelectedForm?.Name;
            set => this.tabPanelControl1.SelectedForm = this.tabPanelControl1.Forms.FirstOrDefault(x => x.Name == value);
        }

        /// <summary>
        /// 添加子窗体
        /// </summary>
        /// <param name="form">窗体实例</param>
        public void AddForm(System.Windows.Forms.Form form)
        {
            this.tabPanelControl1.AddForm(form);
        }

        /// <summary>
        /// 是否包含指定名称的窗体
        /// </summary>
        /// <param name="name">窗体名称</param>
        /// <returns></returns>
        public bool ContainsForm(string name)
        {
            return this.tabPanelControl1.ContainsForm(name);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                ClosePromptForm frm = new ClosePromptForm();
                if (frm.ShowDialog() != DialogResult.OK)
                {
                    e.Cancel = true;
                }
            }
        }
    }
}
